package com.android.JiYclock.expand;

import java.util.Calendar;
import java.util.Date;

import com.android.JiYclock.Alarm;
import com.android.JiYclock.Alarms;
import com.android.JiYclock.Log;
import com.android.JiYclocks.SpecialAlarm;
import com.android.JiYclocks.SpecialAlarms;

import android.content.Context;
import android.os.CountDownTimer;
import android.widget.TextView;

/**
 * 
 * @author BinGe
 * 用于首页的倒计时
 *
 */
public class MyCount extends CountDownTimer {
	
	  private TextView day;
	  private TextView hour;
	  private TextView minute;
	

	 public MyCount(long millisInFuture, long countDownInterval) {     
         super(millisInFuture, countDownInterval);     
     }     
	 
	 public MyCount(long millisInFuture, long countDownInterval,TextView tday,
			 TextView thour,TextView tminute) {     
		 
         super(millisInFuture, countDownInterval);    
         this.day = tday;
         this.hour = thour;
         this.minute = tminute;
         
         
     }     
	 
     @Override     
     public void onFinish() {     
         //tv.setText("finish");        
     }     
     @Override     
     public void onTick(long millisUntilFinished) {     
    	 
         long hours = millisUntilFinished / (1000 * 60 * 60);
         long minutes = millisUntilFinished / (1000 * 60) % 60;
         long days = hours / 24;
         hours = hours % 24;
      	day.setText(String.valueOf(days));
      	hour.setText(String.valueOf(hours));
      	minute.setText(String.valueOf(minutes));
     }    
     
     public static  Long  caculateLastTime(Context context)
     {
    	 Calendar temp = Calendar.getInstance();
       	  temp.setTimeInMillis(System.currentTimeMillis());
     	  SpecialAlarm special =SpecialAlarms.calculateNextAlert(context);
     	  Alarm alarm = Alarms.calculateNextAlert(context);
     	  Long time = Long.MAX_VALUE;
     	  
     	if(alarm==null&&special==null)
     	{
     		time = (long)0;
     	}else if(alarm==null)
     	{  
    
     		time = special.time-System.currentTimeMillis();
     	
     	}else if(special == null){
     		
     		if(alarm.time<System.currentTimeMillis())
     		{
     			temp.setTimeInMillis(alarm.time);
     			temp.add(Calendar.DAY_OF_YEAR, 1);
     			time = temp.getTimeInMillis() - System.currentTimeMillis();
     		}else
     		{
     			time = alarm.time -( System.currentTimeMillis());
     		}
     }else
     	{
         	 if(alarm.time<System.currentTimeMillis())
  		    {
         		temp.setTimeInMillis(alarm.time);
     			temp.add(Calendar.DAY_OF_YEAR, 1);
     			time = (special.time<temp.getTimeInMillis())?special.time:temp.getTimeInMillis();
     			time = time-System.currentTimeMillis();
  		    }else{
     		time =alarm.time;
       	   
	         time = time-(System.currentTimeMillis());
  		    }
     	}
     	return time;
     	
     }
     
     
     
}
